#version： 20230713
#author ： Joe
#Modify ： 2023.7.10  创建工程 完成自动化重启  记录WiFi状态至execl表格
#          2023.7.12  增加dmesg日志记录
#          2023.7.13  增加logcat日志记录  增加测试次数参数         

import time
import os,sys
import datetime
import subprocess

os.chdir("./")              
sys.path.append("./lib")

from openpyxl import Workbook 
from openpyxl import load_workbook

def scanProcess():
    if len(sys.argv) < 2:
        print("Usage: python wifiTest.py <count>")
        exit()
    count = sys.argv[1]
    return int(count)

def restart_device():
    subprocess.run(['adb', 'wait-for-device', 'reboot'])

def check_wifi_status():
    result = subprocess.run(['adb', 'shell', 'ps'], capture_output=True, text=True)
    #print(result.stdout)
    wifi_status = "WiFi is connected" if "wpa_supplicant" in result.stdout else "WiFi is disconnected"
    return wifi_status

def record_to_excel(wifi_status):
    try:
        wb = load_workbook('wifi_status.xlsx')
        sheet = wb.active
    except FileNotFoundError:
        wb = Workbook()
        sheet = wb.active
        sheet['A1'] = 'WiFi Status'
    last_row = sheet.max_row + 1
    sheet.cell(row=last_row, column=1, value=wifi_status)
    wb.save('wifi_status.xlsx')

def get_fail_log():
    subprocess.run(['adb' , 'root'])
    result = subprocess.run(['adb' , 'shell', 'dmesg'], capture_output=True, text=True)
    
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"dmesg_{timestamp}_cout{cout}.txt"
    with open(filename, 'w') as f:
        f.write(result.stdout)
    
    result = subprocess.run(['adb', 'shell', 'logcat', '-d'], capture_output=True, text=False)
    filename = f"logcat_{timestamp}_cout{cout}.txt"
    with open(filename, 'w', encoding='utf-8', errors='ignore') as f:
        f.write(result.stdout.decode('utf-8', errors='ignore'))

if __name__ == "__main__":
    cout = 0                             #计数为0
    stopCount = scanProcess()            #获取测试次数
    print("Test times:",stopCount)       #
    while True:                          #
        cout += 1                        #
        if cout > stopCount:             #
            exit()                       #
                                         #
        restart_device()                 #重启
        time.sleep(45)                   #延迟45s等待开机
        wifi_status = check_wifi_status()#获取WiFi状态
        print(cout,wifi_status)          #
        record_to_excel(wifi_status)     #记录到excel表格
        if wifi_status == "WiFi is disconnected" :
            get_fail_log()               #记录报错日志(包含dmesg和logcat)
            
